#include "mqttClient.h"

MqttClient::MqttClient(const std::string& clientId, const std::string& host, int port)
    : mosqpp::mosquittopp(clientId.c_str()), host_(host), port_(port)
{
    username_pw_set("giaj4ny2f7wusifc", "AIKTtv2H2C");
    connect_async(host_.c_str(), port_, 60);
    loop_start();  // 启动内部线程自动处理消息循环
}

MqttClient::~MqttClient() {
    disconnect();
    loop_stop(true);  // true=等待线程退出
}

void MqttClient::on_message(const struct mosquitto_message* message) {
    if (callback_ && message && message->payloadlen > 0) {
        std::string payload(static_cast<char*>(message->payload), message->payloadlen);
        callback_(message->topic, payload);
    }
}

void MqttClient::publishMessage(const std::string& topic, const std::string& message, int qos, bool retain) {
    publish(nullptr, topic.c_str(), message.size(), message.c_str(), qos, retain);
}

void MqttClient::setMessageCallback(MessageCallback cb) {
    callback_ = cb;
}

void MqttClient::setMessageSubscription(MessageSubscription sub) {
    MessageSub_ = sub;
}

void MqttClient::subscribeTopic(const std::string& topic, int qos) {
    subscribe(nullptr, topic.c_str(), qos);
}

void MqttClient::on_connect(int rc) {
    if (rc == 0) {
        std::cout << "已连接到 MQTT broker" << std::endl;
        MessageSub_();
    } else {
        std::cerr << "连接失败, rc=" << rc << std::endl;
    }
}

void MqttClient::on_disconnect(int rc) {
    std::cout << "连接断开, rc=" << rc << std::endl;
}
